


// 性能监控数据结构
typedef struct {
	float cpu;           // CPU使用率 (%)
	float memory;        // 内存使用率 (%)
	int64 memory_total;  // 总内存 (字节)
	int64 memory_used;   // 已用内存 (字节)
	float network_tx;    // 网络上传速度 (MB/s)
	float network_rx;    // 网络下载速度 (MB/s)
	float disk_read;     // 磁盘读取速度 (MB/s)
	float disk_write;    // 磁盘写入速度 (MB/s)
	xtime timestamp;     // 时间戳
} PerformanceData;

// 磁盘信息结构
typedef struct {
	str mount;           // 挂载点
	int64 total;         // 总空间 (字节)
	int64 used;          // 已用空间 (字节)
	int64 available;     // 可用空间 (字节)
} DiskInfo;

// 全局变量
PerformanceData G_LastPerfData = {0};
xtime G_LastPerfTime = 0;
int64 G_LastNetTx = 0;
int64 G_LastNetRx = 0;
int64 G_LastDiskRead = 0;
int64 G_LastDiskWrite = 0;

// SQL预编译语句
sqlite3_stmt* stmt_perf_add = NULL;


#ifdef _WIN32
#include <windows.h>
#include <psapi.h>
#include <iphlpapi.h>
#pragma comment(lib, "iphlpapi")

// 定义网卡类型常量（兼容旧SDK）
#ifndef IF_TYPE_IEEE80211
#define IF_TYPE_IEEE80211 71  // 无线网卡
#endif

// Windows: 获取CPU使用率（系统整体）
float GetCPUUsage() {
	static ULARGE_INTEGER lastIdleTime = {0};
	static ULARGE_INTEGER lastKernelTime = {0};
	static ULARGE_INTEGER lastUserTime = {0};
	static BOOL bFirstRun = TRUE;
	
	FILETIME idleTime, kernelTime, userTime;
	if (!GetSystemTimes(&idleTime, &kernelTime, &userTime)) {
		return 0.0f;
	}
	
	ULARGE_INTEGER idle, kernel, user;
	idle.LowPart = idleTime.dwLowDateTime;
	idle.HighPart = idleTime.dwHighDateTime;
	kernel.LowPart = kernelTime.dwLowDateTime;
	kernel.HighPart = kernelTime.dwHighDateTime;
	user.LowPart = userTime.dwLowDateTime;
	user.HighPart = userTime.dwHighDateTime;
	
	if (bFirstRun) {
		lastIdleTime = idle;
		lastKernelTime = kernel;
		lastUserTime = user;
		bFirstRun = FALSE;
		return 0.0f;
	}
	
	// 计算时间差
	ULONGLONG idleDiff = idle.QuadPart - lastIdleTime.QuadPart;
	ULONGLONG kernelDiff = kernel.QuadPart - lastKernelTime.QuadPart;
	ULONGLONG userDiff = user.QuadPart - lastUserTime.QuadPart;
	
	// 系统总时间 = 内核时间 + 用户时间（内核时间已包含空闲时间）
	ULONGLONG totalDiff = kernelDiff + userDiff;
	
	// 保存当前值供下次使用
	lastIdleTime = idle;
	lastKernelTime = kernel;
	lastUserTime = user;
	
	// 计算CPU使用率
	if (totalDiff == 0) return 0.0f;
	float cpuUsage = (float)(totalDiff - idleDiff) * 100.0f / (float)totalDiff;
	
	return cpuUsage;
}

// Windows: 获取内存信息
void GetMemoryInfo(int64* total, int64* used) {
	MEMORYSTATUSEX memInfo;
	memInfo.dwLength = sizeof(MEMORYSTATUSEX);
	GlobalMemoryStatusEx(&memInfo);
	*total = memInfo.ullTotalPhys;
	*used = memInfo.ullTotalPhys - memInfo.ullAvailPhys;
}

// Windows: 获取网络流量
void GetNetworkStats(int64* tx, int64* rx) {
	// 使用 IP Helper API 获取网络统计
	PMIB_IFTABLE pIfTable = NULL;
	DWORD dwSize = 0;
	int64 totalTx = 0, totalRx = 0;
	
	// 第一次调用获取所需缓冲区大小
	if (GetIfTable(NULL, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) {
		pIfTable = (MIB_IFTABLE*)xrtMalloc(dwSize);
		
		if (pIfTable != NULL) {
			// 第二次调用获取实际数据
			if (GetIfTable(pIfTable, &dwSize, FALSE) == NO_ERROR) {
				for (DWORD i = 0; i < pIfTable->dwNumEntries; i++) {
					MIB_IFROW* pIfRow = &pIfTable->table[i];
					
					// 跳过回环接口
					if (pIfRow->dwType == MIB_IF_TYPE_LOOPBACK) {
						continue;
					}
					
					// 只统计以太网和无线网卡，过滤虚拟网卡
					if (pIfRow->dwType != IF_TYPE_ETHERNET_CSMACD &&
						pIfRow->dwType != IF_TYPE_IEEE80211) {
						continue;
					}
					
					// 只统计运行中的接口
					if (pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL ||
						pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED) {
						// 累计流量数据
						totalTx += pIfRow->dwOutOctets;
						totalRx += pIfRow->dwInOctets;
					}
				}
			}
			
			xrtFree(pIfTable);
		}
	}
	
	*tx = totalTx;
	*rx = totalRx;
}

// Windows: 获取磁盘IO（模拟数据）
void GetDiskIOStats(int64* read, int64* write) {
	// Windows下获取磁盘IO统计较复杂，这里返回模拟数据
	*read = 0;
	*write = 0;
}

// Windows: 获取磁盘空间信息
int GetDiskList(DiskInfo** disks) {
	int count = 0;
	DiskInfo* list = (DiskInfo*)xrtMalloc(sizeof(DiskInfo) * 26);
	
	DWORD drives = GetLogicalDrives();
	for (int i = 0; i < 26; i++) {
		if (drives & (1 << i)) {
			char root[4] = {(char)('A' + i), ':', '\\', '\0'};
			ULARGE_INTEGER freeBytesAvailable, totalBytes, totalFreeBytes;
			
			if (GetDiskFreeSpaceExA(root, &freeBytesAvailable, &totalBytes, &totalFreeBytes)) {
				list[count].mount = xrtFormat("%c:", 'A' + i);
				list[count].total = totalBytes.QuadPart;
				list[count].available = freeBytesAvailable.QuadPart;
				list[count].used = totalBytes.QuadPart - totalFreeBytes.QuadPart;
				count++;
			}
		}
	}
	
	*disks = list;
	return count;
}

#else
// Linux实现
#include <sys/statvfs.h>
#include <sys/sysinfo.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <ctype.h>

// Linux: 获取CPU使用率
float GetCPUUsage() {
	static long long lastTotal = 0, lastIdle = 0;
	
	FILE* file = fopen("/proc/stat", "r");
	if (!file) return 0.0f;
	
	char buffer[256];
	fgets(buffer, sizeof(buffer), file);
	fclose(file);
	
	long long user, nice, system, idle, iowait, irq, softirq, steal;
	sscanf(buffer, "cpu %lld %lld %lld %lld %lld %lld %lld %lld",
		&user, &nice, &system, &idle, &iowait, &irq, &softirq, &steal);
	
	long long total = user + nice + system + idle + iowait + irq + softirq + steal;
	
	if (lastTotal != 0) {
		long long totalDiff = total - lastTotal;
		long long idleDiff = idle - lastIdle;
		float percent = (float)(totalDiff - idleDiff) / (float)totalDiff * 100.0f;
		lastTotal = total;
		lastIdle = idle;
		return percent;
	}
	
	lastTotal = total;
	lastIdle = idle;
	return 0.0f;
}

// Linux: 获取内存信息
void GetMemoryInfo(int64* total, int64* used) {
	struct sysinfo si;
	if (sysinfo(&si) == 0) {
		*total = si.totalram * si.mem_unit;
		*used = (si.totalram - si.freeram - si.bufferram) * si.mem_unit;
	}
}

// Linux: 获取网络流量
void GetNetworkStats(int64* tx, int64* rx) {
	FILE* file = fopen("/proc/net/dev", "r");
	if (!file) {
		*tx = 0;
		*rx = 0;
		return;
	}
	
	char buffer[256];
	int64 totalRx = 0, totalTx = 0;
	
	// 跳过前两行标题
	fgets(buffer, sizeof(buffer), file);
	fgets(buffer, sizeof(buffer), file);
	
	while (fgets(buffer, sizeof(buffer), file)) {
		char iface[32];
		int64 rxBytes, txBytes;
		if (sscanf(buffer, "%s %lld %*d %*d %*d %*d %*d %*d %*d %lld", 
			iface, &rxBytes, &txBytes) == 3) {
			// 跳过lo接口
			if (strstr(iface, "lo:") == NULL) {
				totalRx += rxBytes;
				totalTx += txBytes;
			}
		}
	}
	fclose(file);
	
	*rx = totalRx;
	*tx = totalTx;
}

// Linux: 获取磁盘IO
void GetDiskIOStats(int64* read, int64* write) {
	FILE* file = fopen("/proc/diskstats", "r");
	if (!file) {
		*read = 0;
		*write = 0;
		return;
	}
	
	char buffer[256];
	int64 totalRead = 0, totalWrite = 0;
	
	while (fgets(buffer, sizeof(buffer), file)) {
		int major, minor;
		char dev[32];
		long long reads, writes;
		
		if (sscanf(buffer, "%d %d %s %*d %*d %lld %*d %*d %*d %lld",
			&major, &minor, dev, &reads, &writes) == 5) {
			// 只统计主设备（如sda, hda等）
			if (major >= 8 && strlen(dev) <= 4) {
				totalRead += reads * 512;  // 扇区转字节
				totalWrite += writes * 512;
			}
		}
	}
	fclose(file);
	
	*read = totalRead;
	*write = totalWrite;
}

// Linux: 获取磁盘空间信息
int GetDiskList(DiskInfo** disks) {
	FILE* file = fopen("/proc/mounts", "r");
	if (!file) {
		*disks = NULL;
		return 0;
	}
	
	DiskInfo* list = (DiskInfo*)xrtMalloc(sizeof(DiskInfo) * 32);
	int count = 0;
	char buffer[512];
	
	while (fgets(buffer, sizeof(buffer), file) && count < 32) {
		char dev[128], mount[256], type[32];
		if (sscanf(buffer, "%s %s %s", dev, mount, type) == 3) {
			// 只统计真实磁盘挂载点
			if (strncmp(dev, "/dev/", 5) == 0 && 
				(strcmp(type, "ext4") == 0 || strcmp(type, "ext3") == 0 ||
				strcmp(type, "xfs") == 0 || strcmp(type, "btrfs") == 0)) {
				
				struct statvfs vfs;
				if (statvfs(mount, &vfs) == 0) {
					list[count].mount = xrtCopyStr(mount, 0);
					list[count].total = vfs.f_blocks * vfs.f_frsize;
					list[count].available = vfs.f_bavail * vfs.f_frsize;
					list[count].used = (vfs.f_blocks - vfs.f_bfree) * vfs.f_frsize;
					count++;
				}
			}
		}
	}
	fclose(file);
	
	*disks = list;
	return count;
}

#endif


// 获取当前性能数据
void GetCurrentPerformanceData(PerformanceData* data) {
	if (!data) return;
	
	xtime now = xrtNow();
	float timeDiff = (float)(now - G_LastPerfTime) / 1000.0f; // 秒
	
	// CPU和内存
	data->cpu = GetCPUUsage();
	GetMemoryInfo(&data->memory_total, &data->memory_used);
	if (data->memory_total > 0) {
		data->memory = (float)data->memory_used / (float)data->memory_total * 100.0f;
	} else {
		data->memory = 0.0f;
	}
	
	// 网络流量
	int64 netTx, netRx;
	GetNetworkStats(&netTx, &netRx);
	if (G_LastPerfTime > 0 && timeDiff > 0 && G_LastNetTx > 0 && G_LastNetRx > 0) {
		// 计算差值并转换为 MB/s
		int64 txDiff = netTx - G_LastNetTx;
		int64 rxDiff = netRx - G_LastNetRx;
		
		// 防止计数器溢出导致负数
		if (txDiff >= 0 && rxDiff >= 0) {
			data->network_tx = (float)txDiff / timeDiff / 1024.0f / 1024.0f;
			data->network_rx = (float)rxDiff / timeDiff / 1024.0f / 1024.0f;
		} else {
			data->network_tx = 0.0f;
			data->network_rx = 0.0f;
		}
	} else {
		data->network_tx = 0.0f;
		data->network_rx = 0.0f;
	}
	G_LastNetTx = netTx;
	G_LastNetRx = netRx;
	
	// 磁盘IO
	int64 diskRead, diskWrite;
	GetDiskIOStats(&diskRead, &diskWrite);
	if (G_LastPerfTime > 0 && timeDiff > 0 && G_LastDiskRead > 0 && G_LastDiskWrite > 0) {
		// 计算差值并转换为 MB/s
		int64 readDiff = diskRead - G_LastDiskRead;
		int64 writeDiff = diskWrite - G_LastDiskWrite;
		
		// 防止计数器溢出导致负数
		if (readDiff >= 0 && writeDiff >= 0) {
			data->disk_read = (float)readDiff / timeDiff / 1024.0f / 1024.0f;
			data->disk_write = (float)writeDiff / timeDiff / 1024.0f / 1024.0f;
		} else {
			data->disk_read = 0.0f;
			data->disk_write = 0.0f;
		}
	} else {
		data->disk_read = 0.0f;
		data->disk_write = 0.0f;
	}
	G_LastDiskRead = diskRead;
	G_LastDiskWrite = diskWrite;
	
	data->timestamp = now;
	G_LastPerfTime = now;
	
	// 保存到全局变量
	G_LastPerfData = *data;
}


// 保存性能数据到数据库
void SavePerformanceData(PerformanceData* data) {
	if (!G_DB || !stmt_perf_add) return;
	
	sqlite3_bind_double(stmt_perf_add, 1, data->cpu);
	sqlite3_bind_double(stmt_perf_add, 2, data->memory);
	sqlite3_bind_int64(stmt_perf_add, 3, data->memory_total);
	sqlite3_bind_int64(stmt_perf_add, 4, data->memory_used);
	sqlite3_bind_double(stmt_perf_add, 5, data->network_tx);
	sqlite3_bind_double(stmt_perf_add, 6, data->network_rx);
	sqlite3_bind_double(stmt_perf_add, 7, data->disk_read);
	sqlite3_bind_double(stmt_perf_add, 8, data->disk_write);
	sqlite3_bind_int64(stmt_perf_add, 9, data->timestamp);
	
	int ret = sqlite3_step(stmt_perf_add);
	if (ret != SQLITE_DONE) {
		printf("!!! ERROR !!! SavePerformanceData - sqlite3_step error: %s\n", sqlite3_errmsg(G_DB->objDB));
	}
	sqlite3_reset(stmt_perf_add);
}


// 后台采集线程（每3秒采集一次）
void* PerformanceCollectThread(void* param) {
	int cleanupCounter = 0;
	while (TRUE) {
		PerformanceData data;
		GetCurrentPerformanceData(&data);
		SavePerformanceData(&data);
		
		// 每1小时清理30天前的数据（600次 * 3秒 = 30分钟）
		cleanupCounter++;
		if (cleanupCounter >= 600) {
			xtime thirtyDaysAgo = xrtNow() - (30LL * 24 * 60 * 60 * 1000);
			str sSQL = xrtFormat("DELETE FROM performance WHERE timestamp < %lld;", thirtyDaysAgo);
			xdoExecute(G_DB, sSQL);
			xrtFree(sSQL);
			cleanupCounter = 0;
		}
		
		// 等待3秒
		#ifdef _WIN32
		Sleep(3000);
		#else
		sleep(3);
		#endif
	}
	return NULL;
}


// 初始化性能监控模块
void Performance_Init() {
	// 创建性能数据表（如果不存在）
	str sCreateTable = 
		"CREATE TABLE IF NOT EXISTS performance ("
		"  id INTEGER PRIMARY KEY AUTOINCREMENT,"
		"  cpu REAL NOT NULL,"
		"  memory REAL NOT NULL,"
		"  memory_total INTEGER NOT NULL,"
		"  memory_used INTEGER NOT NULL,"
		"  network_tx REAL NOT NULL,"
		"  network_rx REAL NOT NULL,"
		"  disk_read REAL NOT NULL,"
		"  disk_write REAL NOT NULL,"
		"  timestamp INTEGER NOT NULL"
		");";
	xdoExecute(G_DB, sCreateTable);
	
	// 创建索引
	xdoExecute(G_DB, "CREATE INDEX IF NOT EXISTS idx_perf_timestamp ON performance(timestamp);");
	
	// 编译SQL语句
	int iRet = sqlite3_prepare_v3(G_DB->objDB, 
		"INSERT INTO performance (cpu, memory, memory_total, memory_used, network_tx, network_rx, disk_read, disk_write, timestamp) "
		"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);", 
		-1, SQL_PREPARE_DEFAULT, &stmt_perf_add, NULL);
	
	if (iRet != SQLITE_OK) {
		printf("!!! ERROR !!! Performance_Init - sqlite3_prepare_v3 error: %s\n", sqlite3_errmsg(G_DB->objDB));
		return;
	}
	
	// 启动后台采集线程
	#ifdef _WIN32
	CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)PerformanceCollectThread, NULL, 0, NULL);
	#else
	pthread_t thread;
	pthread_create(&thread, NULL, PerformanceCollectThread, NULL);
	pthread_detach(thread);
	#endif
	
}


// 卸载性能监控模块
void Performance_Unit() {
	if (stmt_perf_add) {
		sqlite3_finalize(stmt_perf_add);
		stmt_perf_add = NULL;
	}
}


// ========== 服务器探针功能 ==========

// 服务器信息结构
typedef struct {
	str os_type;          // 操作系统类型
	str os_version;       // 操作系统版本
	str hostname;         // 主机名
	str cpu_model;        // CPU型号
	int cpu_cores;        // CPU核心数
	int64 uptime;         // 运行时间（秒）
	str kernel_version;   // 内核版本
	str architecture;     // 系统架构
	str ip_address;       // IP地址（主要网卡）
	str mac_address;      // MAC地址（主要网卡）
} ServerInfo;

#ifdef _WIN32

// Windows: 获取服务器信息
void GetServerInfo(ServerInfo* info) {
	if (!info) return;
	
	// 操作系统类型
	info->os_type = xrtCopyStr("Windows", 7);
	
	// 获取计算机名
	char computerName[256];
	DWORD size = sizeof(computerName);
	if (GetComputerNameA(computerName, &size)) {
		info->hostname = xrtCopyStr(computerName, strlen(computerName));
	} else {
		info->hostname = xrtCopyStr("Unknown", 7);
	}
	
	// 获取系统信息
	SYSTEM_INFO sysInfo;
	GetSystemInfo(&sysInfo);
	info->cpu_cores = sysInfo.dwNumberOfProcessors;
	
	// 系统架构
	// 定义 ARM64 常量（兼容旧 SDK）
	#ifndef PROCESSOR_ARCHITECTURE_ARM64
	#define PROCESSOR_ARCHITECTURE_ARM64 12
	#endif
	
	switch (sysInfo.wProcessorArchitecture) {
		case PROCESSOR_ARCHITECTURE_AMD64:
			info->architecture = xrtCopyStr("x64", 3);
			break;
		case PROCESSOR_ARCHITECTURE_INTEL:
			info->architecture = xrtCopyStr("x86", 3);
			break;
		case PROCESSOR_ARCHITECTURE_ARM:
			info->architecture = xrtCopyStr("ARM", 3);
			break;
		case PROCESSOR_ARCHITECTURE_ARM64:
			info->architecture = xrtCopyStr("ARM64", 5);
			break;
		default:
			info->architecture = xrtCopyStr("Unknown", 7);
	}
	
	// 获取Windows版本
	OSVERSIONINFOEXA osvi;
	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);
	
	// Windows 10及以上需要用RtlGetVersion
	typedef LONG (WINAPI *RtlGetVersionFunc)(PRTL_OSVERSIONINFOW);
	HMODULE hNtdll = GetModuleHandleA("ntdll.dll");
	if (hNtdll) {
		RtlGetVersionFunc pRtlGetVersion = (RtlGetVersionFunc)GetProcAddress(hNtdll, "RtlGetVersion");
		if (pRtlGetVersion) {
			RTL_OSVERSIONINFOW ovi = {0};
			ovi.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOW);
			pRtlGetVersion(&ovi);
			
			if (ovi.dwMajorVersion == 10) {
				if (ovi.dwBuildNumber >= 22000) {
					info->os_version = xrtFormat("Windows 11 (Build %d)", ovi.dwBuildNumber);
				} else {
					info->os_version = xrtFormat("Windows 10 (Build %d)", ovi.dwBuildNumber);
				}
			} else if (ovi.dwMajorVersion == 6) {
				if (ovi.dwMinorVersion == 3) {
					info->os_version = xrtCopyStr("Windows 8.1", 11);
				} else if (ovi.dwMinorVersion == 2) {
					info->os_version = xrtCopyStr("Windows 8", 9);
				} else if (ovi.dwMinorVersion == 1) {
					info->os_version = xrtCopyStr("Windows 7", 9);
				} else {
					info->os_version = xrtFormat("Windows %d.%d", ovi.dwMajorVersion, ovi.dwMinorVersion);
				}
			} else {
				info->os_version = xrtFormat("Windows %d.%d (Build %d)", ovi.dwMajorVersion, ovi.dwMinorVersion, ovi.dwBuildNumber);
			}
			info->kernel_version = xrtFormat("%d.%d.%d", ovi.dwMajorVersion, ovi.dwMinorVersion, ovi.dwBuildNumber);
		}
	}
	
	if (!info->os_version) {
		info->os_version = xrtCopyStr("Windows", 7);
		info->kernel_version = xrtCopyStr("Unknown", 7);
	}
	
	// CPU型号 - 从注册表读取
	HKEY hKey;
	if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
		char cpuName[256];
		DWORD bufSize = sizeof(cpuName);
		if (RegQueryValueExA(hKey, "ProcessorNameString", NULL, NULL, (LPBYTE)cpuName, &bufSize) == ERROR_SUCCESS) {
			// 去除前后空格
			char* start = cpuName;
			while (*start == ' ') start++;
			info->cpu_model = xrtCopyStr(start, strlen(start));
		} else {
			info->cpu_model = xrtCopyStr("Unknown", 7);
		}
		RegCloseKey(hKey);
	} else {
		info->cpu_model = xrtCopyStr("Unknown", 7);
	}
	
	// 系统运行时间（毫秒转秒）
	info->uptime = GetTickCount64() / 1000;
	
	// 获取网络信息（IP和MAC地址）
	PMIB_IFTABLE pIfTable = NULL;
	DWORD dwSize = 0;
	info->ip_address = NULL;
	info->mac_address = NULL;
	
	if (GetIfTable(NULL, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) {
		pIfTable = (MIB_IFTABLE*)xrtMalloc(dwSize);
		
		if (pIfTable != NULL && GetIfTable(pIfTable, &dwSize, FALSE) == NO_ERROR) {
			// 遍历网卡，找到第一个活动的以太网或无线网卡
			for (DWORD i = 0; i < pIfTable->dwNumEntries; i++) {
				MIB_IFROW* pIfRow = &pIfTable->table[i];
				
				// 跳过回环接口
				if (pIfRow->dwType == MIB_IF_TYPE_LOOPBACK) {
					continue;
				}
				
				// 只获取以太网和无线网卡
				if (pIfRow->dwType != IF_TYPE_ETHERNET_CSMACD &&
					pIfRow->dwType != IF_TYPE_IEEE80211) {
					continue;
				}
				
				// 只获取运行中的接口
				if (pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL ||
					pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED) {
					
					// 获取MAC地址
					if (pIfRow->dwPhysAddrLen == 6) {
						info->mac_address = xrtFormat("%02X:%02X:%02X:%02X:%02X:%02X",
							pIfRow->bPhysAddr[0], pIfRow->bPhysAddr[1],
							pIfRow->bPhysAddr[2], pIfRow->bPhysAddr[3],
							pIfRow->bPhysAddr[4], pIfRow->bPhysAddr[5]);
					}
					
					// 获取IP地址（需要使用GetAdaptersInfo）
					PIP_ADAPTER_INFO pAdapterInfo = NULL;
					ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
					pAdapterInfo = (IP_ADAPTER_INFO*)xrtMalloc(ulOutBufLen);
					
					if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
						xrtFree(pAdapterInfo);
						pAdapterInfo = (IP_ADAPTER_INFO*)xrtMalloc(ulOutBufLen);
					}
					
					if (pAdapterInfo && GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == NO_ERROR) {
						PIP_ADAPTER_INFO pAdapter = pAdapterInfo;
						while (pAdapter) {
							// 匹配MAC地址
							if (pAdapter->AddressLength == 6 &&
								memcmp(pAdapter->Address, pIfRow->bPhysAddr, 6) == 0) {
								info->ip_address = xrtCopyStr(pAdapter->IpAddressList.IpAddress.String,
									strlen(pAdapter->IpAddressList.IpAddress.String));
								break;
							}
							pAdapter = pAdapter->Next;
						}
					}
					
					if (pAdapterInfo) {
						xrtFree(pAdapterInfo);
					}
					
					break; // 只获取第一个活动网卡
				}
			}
			
			xrtFree(pIfTable);
		}
	}
	
	// 如果没有获取到，设置默认值
	if (!info->ip_address) {
		info->ip_address = xrtCopyStr("Unknown", 7);
	}
	if (!info->mac_address) {
		info->mac_address = xrtCopyStr("Unknown", 7);
	}
}

#else

// Linux: 获取服务器信息
void GetServerInfo(ServerInfo* info) {
	if (!info) return;
	
	// 操作系统类型
	info->os_type = xrtCopyStr("Linux", 5);
	
	// 获取主机名
	char hostname[256];
	if (gethostname(hostname, sizeof(hostname)) == 0) {
		info->hostname = xrtCopyStr(hostname, strlen(hostname));
	} else {
		info->hostname = xrtCopyStr("Unknown", 7);
	}
	
	// CPU核心数
	info->cpu_cores = sysconf(_SC_NPROCESSORS_ONLN);
	
	// 系统架构
	struct utsname uts;
	if (uname(&uts) == 0) {
		info->architecture = xrtCopyStr(uts.machine, strlen(uts.machine));
		info->kernel_version = xrtCopyStr(uts.release, strlen(uts.release));
	} else {
		info->architecture = xrtCopyStr("Unknown", 7);
		info->kernel_version = xrtCopyStr("Unknown", 7);
	}
	
	// 读取操作系统版本信息
	FILE* file = fopen("/etc/os-release", "r");
	if (file) {
		char buffer[256];
		char* prettyName = NULL;
		
		while (fgets(buffer, sizeof(buffer), file)) {
			if (strncmp(buffer, "PRETTY_NAME=", 12) == 0) {
				char* start = buffer + 12;
				if (*start == '"') start++;
				char* end = strchr(start, '"');
				if (end) *end = '\0';
				end = strchr(start, '\n');
				if (end) *end = '\0';
				prettyName = xrtCopyStr(start, strlen(start));
				break;
			}
		}
		fclose(file);
		
		if (prettyName) {
			info->os_version = prettyName;
		} else {
			info->os_version = xrtCopyStr("Linux", 5);
		}
	} else {
		info->os_version = xrtCopyStr("Linux", 5);
	}
	
	// CPU型号
	file = fopen("/proc/cpuinfo", "r");
	if (file) {
		char buffer[256];
		char* modelName = NULL;
		
		while (fgets(buffer, sizeof(buffer), file)) {
			if (strncmp(buffer, "model name", 10) == 0) {
				char* colon = strchr(buffer, ':');
				if (colon) {
					char* start = colon + 1;
					while (*start == ' ' || *start == '\t') start++;
					char* end = strchr(start, '\n');
					if (end) *end = '\0';
					modelName = xrtCopyStr(start, strlen(start));
					break;
				}
			}
		}
		fclose(file);
		
		if (modelName) {
			info->cpu_model = modelName;
		} else {
			info->cpu_model = xrtCopyStr("Unknown", 7);
		}
	} else {
		info->cpu_model = xrtCopyStr("Unknown", 7);
	}
	
	// 系统运行时间
	struct sysinfo si;
	if (sysinfo(&si) == 0) {
		info->uptime = si.uptime;
	} else {
		info->uptime = 0;
	}
	
	// 获取网络信息（IP和MAC地址）
	info->ip_address = NULL;
	info->mac_address = NULL;
	
	// 读取/proc/net/route找到默认网卡
	char defaultIface[32] = {0};
	file = fopen("/proc/net/route", "r");
	if (file) {
		char buffer[256];
		fgets(buffer, sizeof(buffer), file); // 跳过标题行
		
		while (fgets(buffer, sizeof(buffer), file)) {
			char iface[32];
			unsigned long destination;
			if (sscanf(buffer, "%s %lx", iface, &destination) == 2) {
				// 找到默认路由（destination = 0）
				if (destination == 0 && strcmp(iface, "lo") != 0) {
					strncpy(defaultIface, iface, sizeof(defaultIface) - 1);
					break;
				}
			}
		}
		fclose(file);
	}
	
	// 如果没有找到默认路由，尝试eth0或ens33
	if (strlen(defaultIface) == 0) {
		if (access("/sys/class/net/eth0", F_OK) == 0) {
			strcpy(defaultIface, "eth0");
		} else if (access("/sys/class/net/ens33", F_OK) == 0) {
			strcpy(defaultIface, "ens33");
		} else if (access("/sys/class/net/ens32", F_OK) == 0) {
			strcpy(defaultIface, "ens32");
		}
	}
	
	if (strlen(defaultIface) > 0) {
		// 获取MAC地址
		char macPath[256];
		snprintf(macPath, sizeof(macPath), "/sys/class/net/%s/address", defaultIface);
		file = fopen(macPath, "r");
		if (file) {
			char macAddr[32];
			if (fgets(macAddr, sizeof(macAddr), file)) {
				char* end = strchr(macAddr, '\n');
				if (end) *end = '\0';
				// 转换为大写
				for (char* p = macAddr; *p; p++) {
					*p = toupper(*p);
				}
				info->mac_address = xrtCopyStr(macAddr, strlen(macAddr));
			}
			fclose(file);
		}
		
		// 获取IP地址（使用ioctl）
		int sock = socket(AF_INET, SOCK_DGRAM, 0);
		if (sock >= 0) {
			struct ifreq ifr;
			memset(&ifr, 0, sizeof(ifr));
			strncpy(ifr.ifr_name, defaultIface, IFNAMSIZ - 1);
			
			if (ioctl(sock, SIOCGIFADDR, &ifr) == 0) {
				struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr;
				char* ipStr = inet_ntoa(addr->sin_addr);
				if (ipStr) {
					info->ip_address = xrtCopyStr(ipStr, strlen(ipStr));
				}
			}
			
			close(sock);
		}
	}
	
	// 如果没有获取到，设置默认值
	if (!info->ip_address) {
		info->ip_address = xrtCopyStr("Unknown", 7);
	}
	if (!info->mac_address) {
		info->mac_address = xrtCopyStr("Unknown", 7);
	}
}

#endif

// 释放服务器信息
void FreeServerInfo(ServerInfo* info) {
	if (!info) return;
	if (info->os_type) xrtFree(info->os_type);
	if (info->os_version) xrtFree(info->os_version);
	if (info->hostname) xrtFree(info->hostname);
	if (info->cpu_model) xrtFree(info->cpu_model);
	if (info->kernel_version) xrtFree(info->kernel_version);
	if (info->architecture) xrtFree(info->architecture);
	if (info->ip_address) xrtFree(info->ip_address);
	if (info->mac_address) xrtFree(info->mac_address);
}

